
import SwiftUI
import UIKit

struct MarkedTextField: UIViewRepresentable {
    @Binding var text: String
    var placeholder: String = ""
    var borderStyle:UITextField.BorderStyle = .none
    var maxLength:Int = 0
    
    private let textField = UITextField(frame: .zero)
    
 
    
    func makeUIView(context: UIViewRepresentableContext<MarkedTextField>) -> UITextField {
        textField.delegate = context.coordinator
        return textField
    }
    func updateUIView(_ uiView: UITextField, context: UIViewRepresentableContext<MarkedTextField>) {}
    func makeCoordinator() -> Coordinator { Coordinator(self,maxLength:maxLength) }
    
    
    
    final class Coordinator: NSObject, UITextFieldDelegate {
        
        var markedTextField: MarkedTextField
        var maxLength: Int
        
        init(_ markedTextField: MarkedTextField,maxLength:Int) {
            self.markedTextField = markedTextField
            self.maxLength = maxLength
            super.init()
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(Self.textDidchange(_:)),
                                                   name: UITextField.textDidChangeNotification,
                                                   object: markedTextField.textField)
        }
        
        
        deinit {
            NotificationCenter.default.removeObserver(self)
        }
        
        @objc private func textDidchange(_ notification: Notification) {
            let textField = markedTextField.textField
            if textField.markedTextRange == nil {
                markedTextField.text = textField.text ?? String()
            }
        }
        
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            
            if string.isEmpty {
                return true
            }
            let currentText = textField.text ?? ""
            let replacementText = (currentText as NSString).replacingCharacters(in: range, with: string)
            if (maxLength > 0 && replacementText.count > maxLength) {
                return false
            }
            return true
        }
    }
}
